# -*- coding: utf-8 -*-            
# @Author : chenliang
# @Time : 2025/1/15 15:31

from flask import Flask, render_template, request,send_file, Response
from Common.business_common_tool import BusinessCommonTools
from Common.get_sql_object import GetSqlObject
import sqlite3
import io
from datetime import datetime
import zipfile
from tool import driver_download
from urllib.parse import quote
from query_driver_bill import driver_bill
import requests





app = Flask(__name__)


DATABASE = 'database.db'


def get_db():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/search')
def search():
    query = request.args.get('q')
    query_phone = request.args.get('h')
    # # 从查询参数或表单数据中获取按钮来源
    source = request.args.get('source')  # GET 方法
    if query or query_phone:
        mysql_source = GetSqlObject.get_instance("PRO")
        query_waybill_list = BusinessCommonTools().waybill_search('PRO', query,query_phone, mysql_source)

        # db = get_db()
        # cur = db.cursor()
        # cur.execute("SELECT * FROM your_table WHERE your_column LIKE ?", ('%' + query + '%',))
        # results = cur.fetchall()
        return render_template('search.html', results=query_waybill_list,source =source)
    return render_template('search.html', message='No search query provided.',source =source)

@app.route('/search_test')
def search_test():
    query = request.args.get('a')
    query_phone = request.args.get('h')

    # # 从查询参数或表单数据中获取按钮来源
    source = request.args.get('source')  # GET 方法
    if query:
        mysql_source = GetSqlObject.get_instance("test")
        query_waybill_list = BusinessCommonTools().waybill_search('test', query,query_phone, mysql_source)

        # db = get_db()
        # cur = db.cursor()
        # cur.execute("SELECT * FROM your_table WHERE your_column LIKE ?", ('%' + quePROry + '%',))
        # results = cur.fetchall()
        return render_template('search.html', results=query_waybill_list,source=source)
    return render_template('search.html', message='No search query provided.',source=source)



@app.route('/download_form')
def download_form():
    return '''
    <!DOCTYPE html>
    <html>
    <body>
        <h3>输入时间参数（格式：YYYY-MM），生成 ZIP 文件</h3>
        <form action="/download_zip" method="POST">
            <input type="text" name="time_param" placeholder="例如：2025-06" required>
            <input type="submit" value="生成并下载">
        </form>
    </body>
    </html>
    '''


@app.route('/download_zip', methods=['POST'])
def download_zip():
    # 1. 获取前端提交的时间参数
    time_param = request.form.get('time_param', '').strip()

    # 2. 验证时间参数格式（YYYY-MM）
    if not validate_time_format(time_param):
        return "时间格式错误，请输入 YYYY-MM（例如：2025-06）", 400

    # 3. 生成 ZIP 文件内容（示例逻辑：创建几个文本文件）
    #zip_buffer = generate_zip(time_param)
    driver=driver_download.driver('2025-06')
    print(driver)

    for i in driver:
        driver_dict=driver_download.driver_down(i)

        print(driver_dict)
        print("====")
        file_stream = io.BytesIO()
        file_stream.write(driver_dict.content)  # 替换为你的实际 ZIP 内容
        file_stream.seek(0)  # 将流指针回到开头

        # 设置响应头，触发浏览器下载
        response = Response(file_stream, mimetype='application/zip')
        filename = f"{i['name']}_{i['phone']}.zip"
        encoded_filename = quote(filename)  # 或使用 quote(filename, encoding='utf-8')

        response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"

        return response



def validate_time_format(time_str):
    """验证时间格式是否为 YYYY-MM"""
    try:
        datetime.strptime(time_str, "%Y-%m")
        return True
    except ValueError:
        return False

@app.route('/driver_excel', methods=['POST'])
def driver_excel():
    # 1. 获取前端提交的时间参数
    now = datetime.now()
    time_param = request.form.get('driver_param', '').strip()
    print(time_param)
    file_url=driver_bill().bill_excel(time_param)
    name = 11
    #file_url = 'http://47.116.122.206/New_driver/司机账单/2025-07-16.xlsx'
    response = requests.get(file_url, stream=True)
    if response.status_code == 200:
        # 将文件流返回给客户端，触发下载
        return Response(
            response.iter_content(chunk_size=1024),
            headers={
                "Content-Disposition": f"attachment; filename={now}.xlsx",
                "Content-Type": response.headers['Content-Type']
            }
        )
    return "文件下载失败", 500







if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)